package com.ruoyi.web.controller.sale;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.ruoyi.commodity.service.IProductService;
import com.ruoyi.common.core.domain.FreightMethod;
import com.ruoyi.common.core.domain.ShipmentStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.sale.domain.ApprovalProcess;
import com.ruoyi.sale.domain.Plan;
import com.ruoyi.sale.domain.PlanProcess;
import com.ruoyi.sale.domain.ProductAuth;
import com.ruoyi.sale.domain.vo.PlanProcessLogVo;
import com.ruoyi.sale.domain.vo.PlanVo;
import com.ruoyi.sale.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 销售中心Controller
 * 
 * @author ruoyi
 * @date 2023-10-11
 */
@RestController
@RequestMapping("/sale/plan")
public class PlanController extends BaseController
{
    @Autowired
    private IPlanService planService;

    @Autowired
    private IShipmentStatusService shipmentStatusService;

    @Autowired
    private IProductService productService;

    @Autowired
    private IFreightMethodService freightMethodService;

    @Autowired
    private IApprovalProcessService approvalProcessService;

    @Autowired
    private IPlanProcessService planProcessService;

    @Autowired
    private IPlanProcessLogService planProcessLogService;
    /**
     * 查询销售计划列表
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/list")
    public TableDataInfo list(Plan plan)
    {
        if (plan == null || plan.getUserId() == null) { // 这里的XXX需要替换为plan对象中的属性名
            startPage();
        }
        List<Plan> list = planService.selectPlanList(plan,false);
        return getDataTable(list);
    }

    /**
     * 备货计划处查询销售计划列表
     */
    @GetMapping("/stockPlan/list")
    public TableDataInfo stockPlanList(Plan plan)
    {
        if (plan == null || plan.getUserId() == null) { // 这里的XXX需要替换为plan对象中的属性名
            startPage();
        }
        List<Plan> list = planService.selectPlanList(plan,true);
        return getDataTable(list);
    }

    /**
     * 导出销售计划列表
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:export')")
    @Log(title = "销售计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Plan plan)
    {
        List<Plan> list = planService.selectPlanList(plan,false);
        ExcelUtil<Plan> util = new ExcelUtil<Plan>(Plan.class);
        util.exportExcel(response, list, "销售计划数据");
    }

    /**
     * 获取销售计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(planService.selectPlanById(id));
    }

    /**
     * 点击提前结束按钮的时候查询是否有关联的采购订单
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:query')")
    @GetMapping(value = "/SearchRelatedPurchaseOrders/{planNumber}/{detailId}")
    public AjaxResult SearchRelatedPurchaseOrders(@PathVariable("planNumber") String planNumber,
                                                  @PathVariable("detailId") String detailId)
    {
        return success(planService.SearchRelatedPurchaseOrders(planNumber,detailId));
    }

    /**
     * 新增销售计划
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:add')")
    @Log(title = "销售计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Plan plan, @RequestParam(value = "componentPath", required = false) String componentPath)
    {
        plan.setUserId(getUserId());
        return toAjax(planService.insertPlan(plan, componentPath, getUserId()));
    }

    /**
     * 修改销售计划
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:edit')")
    @Log(title = "销售计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Plan plan)
    {
        approvalProcessService.updateStatusInt(plan.getId());
        return toAjax(planService.updatePlan(plan));
    }

    /**
     * 删除销售计划
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:remove')")
    @Log(title = "销售计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(planService.deletePlanByIds(ids));
    }


    /**
     * 提前结束销售计划
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:end')")
    @Log(title = "销售计划", businessType = BusinessType.DELETE)
    @PostMapping("/end")
    public AjaxResult endPlan(@RequestParam("planId") Long planId,
                             @RequestParam("detailId") String detailId,
                             @RequestParam("count") Integer count)
    {
        return toAjax(planService.endPlanById(planId,detailId,count));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/shipmentStatusTree")
    public AjaxResult shipmentStatusTree(ShipmentStatus shipmentStatus){
        return success(shipmentStatusService.selectShipmentStatusTreeList(shipmentStatus));
    }

    /**
     * 批量查询产品
     * @return
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/selectProductListById/{ids}")
    public AjaxResult selectProductListById(@PathVariable Long[] ids){
        return success(productService.selectProductListById(ids));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/freightMethodTree")
    public AjaxResult freightMethodTree(FreightMethod freightMethod){
        return success(freightMethodService.selectFreightMethodTreeList(freightMethod));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @PutMapping("/updatePlanStatusById/{id}")
    public  AjaxResult updatePlanStatusById(@PathVariable Long id){
        Plan plan = planService.selectPlanById(id);
        if(plan.getPlanStatus().equals("4")) {
            ApprovalProcess approvalProcess = new ApprovalProcess();
            approvalProcess.setPlanId(id);
            List<ApprovalProcess> approvalProcesses = approvalProcessService.selectApprovalProcessList(approvalProcess);
            for (ApprovalProcess newApprovalProcess:approvalProcesses) {
                if(newApprovalProcess.getStatus().equals("0")){
                    return error("该订单被上级审核过！");
                }
            }
            approvalProcessService.updateStatusInt(plan.getId());
            return success(planService.updatePlanStatusById(id));
        }
        return error("只支持未审核，才能撤回！");
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/selectPostUserDept/{userId}/{deptId}/{id}")
    public AjaxResult selectPostUserDept(@PathVariable Long userId,@PathVariable Long deptId,@PathVariable Long id){
        return success(planService.selectPostUserDept(userId, deptId,id));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @PutMapping("/updateApprovalProcess")
    public AjaxResult updateApprovalProcess(@RequestBody ApprovalProcess approvalProcess){
        approvalProcess.setUserId(getUserId());
        return success(approvalProcessService.updateApprovalProcess(approvalProcess,approvalProcess.getFlag()));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/selectApprovalProcessList/{planId}")
    public AjaxResult selectApprovalProcessList(@PathVariable Long planId){
        ApprovalProcess approvalProcess = new ApprovalProcess();
        approvalProcess.setPlanId(planId);
        return success(approvalProcessService.selectApprovalProcessList(approvalProcess));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody ApprovalProcess approvalProcess){
        approvalProcess.setUserId(getUserId());
        return success(planService.updateStatus(approvalProcess));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/selectPlanReviewed")
    public AjaxResult selectPlanReviewed(Plan plan){
        return success(planService.selectPlanReviewed(plan));
    }

    @PreAuthorize("@ss.hasPermi('sale:plan:list')")
    @GetMapping("/selectPlanInitiated/{userId}")
    public AjaxResult selectPlanInitiated(@PathVariable Long userId){
        return success(planService.selectPlanInitiated(userId));
    }

    /**
     * 通过店铺来查询关联的产品
     * @param productAuth 店铺条件
     * @return 结果
     */
    @GetMapping("/selectItemPlan")
    public TableDataInfo selectItemPlan(ProductAuth productAuth){
//        PageInfo<ProductAuth> productAuthPageInfo = planService.selectItemPlan(productAuth);
        List<ProductAuth> productAuths = planService.selectItemPlan(productAuth);
//        return new TableDataInfo(productAuthPageInfo.getList(),(int)productAuthPageInfo.getTotal());
        return getDataTable(productAuths);
    }

    @PostMapping("/selectPairId")
    public AjaxResult selectPairId(@RequestBody Plan plan){
        return success(planService.selectPairId(plan));
    }

    /**
     * 待我审核的销售计划
     * @param plan
     * @return 结果
     */
    @GetMapping("/getPlanWaitProcessList")
    public TableDataInfo getPlanWaitProcessList(Plan plan)
    {
        if (plan == null || plan.getUserId() == null) { // 这里的XXX需要替换为plan对象中的属性名
            startPage();
        }
        List<Plan> list = planService.getPlanWaitProcessList(plan);
        return getDataTable(list);
    }
    /**
     * 我已审核的销售计划
     * @param plan
     * @return
     */
    @GetMapping("/getPlanReadyProcessList")
    public TableDataInfo getPlanReadyProcessList(PlanVo plan){
        startPage();
        List<PlanVo> list = planProcessService.getPlanReadyProcessList(plan);
        return getDataTable(list);
    }
    /**
     * 我发起的销售计划
     * @param plan
     * @return
     */
    @GetMapping("/getPlanMyProcessList")
    public TableDataInfo getPlanMyProcessList(PlanVo plan){
        startPage();
        List<PlanVo> list = planProcessService.getPlanMyProcessList(plan);
        return getDataTable(list);
    }
    /**
     * 更新审批结果
     * @param planProcess
     * @return 结果
     */
    @PutMapping("/updatePlanProcessStatus")
    public AjaxResult updatePlanProcessStatus(@RequestBody PlanProcess planProcess){
        planProcess.setReviewerId(getUserId());
        return success(planProcessService.updatePlanProcessStatus(planProcess));
    }
    /**
     * 查询审核流程
     * @param planId
     * @return
     */
    @GetMapping("/getPlanProcessList/{planId}")
    public AjaxResult getPlanProcessList(@PathVariable Long planId){
        return success(planProcessService.getPlanProcessList(planId));
    }
    /**
     * 查询审核记录数据
     * @param planProcessLog
     * @return
     */
    @GetMapping("/selectPlanProcessLogList")
    public TableDataInfo selectPlanProcessLogList(PlanProcessLogVo planProcessLog){
        startPage();
        List<PlanProcessLogVo> planProcessLogs = planProcessLogService.selectPlanProcessLogList(planProcessLog);
        return getDataTable(planProcessLogs);
    }
    /**
     * 撤回销售计划
     */
    @PreAuthorize("@ss.hasPermi('sale:plan:revoke')")
    @PostMapping("/revokePlan")
    public AjaxResult revokePlan(@RequestBody Plan plan, @RequestParam("componentPath") String componentPath)
    {
        if(plan.getId() == null){
            throw new ServiceException("采购计划ID为空。");
        }
        if(plan.getRemark() == null){
            throw new ServiceException("撤回备注不能为空。");
        }
        return toAjax(planService.revokePlan(plan,getNickname(),getUserId(),componentPath));
    }
}